#ifndef WEATHERTOOL
#define WEATHERTOOL
#include<QString>
#include<QMap>
#include<QFile>
#include<QJsonDocument>
#include<QJsonArray>
#include<QJsonObject>
#include<QJsonParseError>
class WeatherTool{
public:
    static QString getCityCode(QString cityName){
        if(mCityMap.isEmpty()){
            initCityMap();
        }
        //没有找到则返回end函数
        QMap<QString,QString>::iterator it=mCityMap.find(cityName);
        if(it==mCityMap.end()){
            it=mCityMap.find(cityName+"市");
        }
        if(it!=mCityMap.end()){
            return it.value();
        }
        return "";
    }
private:
    //key 城市 value编号
    static QMap<QString,QString> mCityMap;

    static void initCityMap(){
        //读取文件
        QString filePath="E:\\c++\\qt\\code\\weather\\citycode.json";
        QFile file(filePath);
        file.open(QIODevice::ReadOnly|QIODevice::Text);
        if(!file.isOpen())
        {
            qDebug()<<"打开失败";
            return;
        }
        QByteArray json=file.readAll();
        file.close();
        //解析json 写入到map
        QJsonParseError err;
        QJsonDocument doc=QJsonDocument::fromJson(json,&err);
        if(err.error!=QJsonParseError::NoError)
            return;
        if(!doc.isArray())
            return;
        QJsonArray cities=doc.array();
        for(int i=0;i<cities.size();i++){
            QString city=cities[i].toObject().value("city_name").toString();
            QString code=cities[i].toObject().value("city_code").toString();
            if(code.size()>0)
                mCityMap.insert(city,code);
        }
    }
};
QMap<QString,QString> WeatherTool::mCityMap={};

#endif // WEATHERTOOL

